﻿using mozhi.smarterp.Finance.Basedatas.Events;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.Querys;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;

namespace mozhi.smarterp.Finance.Basedatas.EventHandlers
{
    public class DataAssociationRemoveEventHandler : IDistributedEventHandler<DataAssociationRemoveEvent>,
          ITransientDependency
    {
        private IDataAssociationRepository _dataAssociationsRepository;

        public DataAssociationRemoveEventHandler(IDataAssociationRepository dataAssociationsRepository)
        {
            _dataAssociationsRepository = dataAssociationsRepository;
        }

        public async Task HandleEventAsync(DataAssociationRemoveEvent eventData)
        {
            //移除关联
            var associations = await _dataAssociationsRepository.FindAsync(new DataAssociationQuery() { OccupantId = eventData.OccupantId, OccupiedId = eventData.OccupiedId });

            if (associations.Count == 0)
                return;

            await _dataAssociationsRepository.DeleteAsync(associations.First());
        }
    }
}
